/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utility.com.treeTable;

import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Action;
import javax.swing.SwingUtilities;

/**
 *
 * @author jay
 */
public class TreeTableCellListener implements PropertyChangeListener, Runnable {
 
    private TreeTable table;
    private Action action;

    private int row;
    private int column;
    private Object oldValue;
    private Object newValue;

    public int getColumn() {return column;}
    public Object getNewValue()	{return newValue;}
    public Object getOldValue()	{return oldValue;}
    public int getRow() {return row;}
    public TreeTable getTable() {return table;}
    
    public TreeTableCellListener(TreeTable table, Action action) {
	this.table = table;
	this.action = action;
	this.table.addPropertyChangeListener(this);
    }

    private TreeTableCellListener(TreeTable table, int row, int column, Object oldValue, Object newValue) {
	this.table = table;
	this.row = row;
	this.column = column;
	this.oldValue = oldValue;
	this.newValue = newValue;
    }
    
    private void processEditingStarted() {
        SwingUtilities.invokeLater(this);
    }
    
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if ("tableCellEditor".equals(evt.getPropertyName())) {
            if (table.isEditing()) {processEditingStarted();}
            else {processEditingStopped();}
        }
    }

    @Override
    public void run() {
        row = table.convertRowIndexToModel( table.getEditingRow() );
	column = table.convertColumnIndexToModel( table.getEditingColumn() );
	oldValue = table.getModel().getValueAt(row, column);
	newValue = "";
    }
    
    private void processEditingStopped() {
        newValue = table.getModel().getValueAt(row, column);
        
        if (newValue==null) {newValue="";}
        if (oldValue==null) {oldValue="";}
        
	if (! newValue.equals(oldValue)) {
            TreeTableCellListener tcl = new TreeTableCellListener(
                getTable(), getRow(), getColumn(), getOldValue(), getNewValue());

            ActionEvent event = new ActionEvent(tcl, ActionEvent.ACTION_PERFORMED, "");
            action.actionPerformed(event);
	}
    }
    
}
